import 'package:carousel_slider/carousel_slider.dart';
import 'package:flutter/material.dart';
import 'package:hxdj/common/colors/my_colors.dart';
import 'package:hxdj/common/components/my_cache_network_image.dart';

class MyBannerView extends StatefulWidget {
  final List<String> imgList; //demolist
  final void Function(int index) select;
  final double? height;
  const MyBannerView(this.imgList, {super.key, required this.select, this.height = 200});

  @override
  State<MyBannerView> createState() => _MyBannerViewState();
}

class _MyBannerViewState extends State<MyBannerView> {
  final CarouselController _buttonCarouselController = CarouselController();
  int _currentIndex = 0;

  @override
  Widget build(BuildContext context) {

    return Stack(
      alignment: Alignment.center,
      children: [
        CarouselSlider(
          options: CarouselOptions(
              height: widget.height,
              aspectRatio: 2.0,
              enlargeCenterPage: false,
              viewportFraction: 1.0,
              autoPlay: true,
              onPageChanged: (index, _) {
                setState(() {
                  _currentIndex = index;
                });
              }),
          items: widget.imgList.map((i) {
            return Builder(
              builder: (BuildContext context) {
                return GestureDetector(
                  onTap: () {
                    widget.select(_currentIndex);
                  },
                  child: Hero(
                    tag: i,
                    child: SizedBox(
                        width: MediaQuery.of(context).size.width,
                        child: MyCachedNetworkImage(
                          imageUrl: i,
                          fit: BoxFit.cover,
                        )),
                  ),
                );
              },
            );
          }).toList(),
          carouselController: _buttonCarouselController,
        ),
        Positioned(
          bottom: 30,
          child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: widget.imgList.map((e) {
                int idx = widget.imgList.indexOf(e);
                return GestureDetector(
                  onTap: () => _buttonCarouselController.animateToPage(idx),
                  child: Container(
                    width: 6,
                    height: 6,
                    decoration: ShapeDecoration(
                      color: idx == _currentIndex ? Colors.white : MyColours.textGray,
                      shape: RoundedRectangleBorder(borderRadius: BorderRadiusDirectional.circular(3)),
                    ),
                    margin: const EdgeInsets.symmetric(vertical: 0.0, horizontal: 4.0),
                  ),
                );
              }).toList()),
        )
      ],
    );
  }
}
